//
//  LTQUserViewModel.swift
//  WeiBoProject
//
//  Created by MAC on 16/2/29.
//  Copyright © 2016年 LTQ. All rights reserved.
//

import UIKit
import AFNetworking

class LTQUserViewModel: NSObject {
    
//    设计一个单例
    static let shareInstance = LTQUserViewModel()
    
    var userModel: LTQUserModel?{
        return LTQUserModel.readUserModel("account.plist")
    }
    
    var access_token:String?{
        return userModel?.access_token
    }
    
    var isLogin: Bool? {
        
        // 1. 如果 token 有值，说明登录成功
        // 2. 如果没有过期，说明登录有效
        return userModel?.access_token != nil && !isExpried
    }
/// 判断账户是否过期
    private var isExpried:Bool{
        
        // 判断用户账户过期日期与当前系统日期`进行比较`
        // 自己改写日期，测试逻辑是否正确，创建日期的时候，如果给定 负数，返回比当前时间早的日期
        // account?.expiresDate = NSDate(timeIntervalSinceNow: -3600)
        
        // 如果 account 为 nil，不会调用后面的属性，后面的比较也不会继续...
        
        if userModel?.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            return false
        }
        return true
    }
    
    
    func loadToken(code:String,success:()->(),failure:()->()){
        
        let afn = AFHTTPSessionManager()
        
        //        修改AFN支持content-type: text/plain格式
        afn.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        let param = [
            "client_id": App_KEY,
            "client_secret":App_SECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":App_URL
        ]
        
        afn.POST("https://api.weibo.com/oauth2/access_token", parameters: param, progress: nil, success: { (_, JSON) -> Void in
            
            //            将JSON传过来值转成 字典 String：NSObject形式
            if  let Odict = JSON as? [String: NSObject]{
                
                let  userModel = LTQUserModel(dic: Odict)
                
                self.getPersonInfo(userModel, success: success, failure: failure)
                
            }
            
            }) { (_, error) -> Void in
                print(error)
                failure()
        }
        
    }
    
    //token存放在模型中，通过传递模型，拿到token
    
    //    还是发送网络请求获取数据
    func getPersonInfo (userInfo: LTQUserModel,success:()->(),failure:()->()){
        
        let afn = AFHTTPSessionManager()
        let param  = ["access_token":userInfo.access_token ?? "",
            "uid":userInfo.uid ?? ""
        ]
        
        afn.GET("https://api.weibo.com/2/users/show.json", parameters: param, progress: nil, success: { (_, JSON) -> Void in
            
            print(JSON)
            if let dic = JSON as? [String:NSObject]{
                
                // userModel.profile_image_url是 String类型的
                // dic["profile_image_url"] 是NSObject
                
                userInfo.screen_name = dic["screen_name"] as? String
                
                userInfo.profile_image_url = dic["profile_image_url"] as? String
                
                userInfo.save("account.plist")
                
                success()
                
            }
            
            }) { (_, error) -> Void in
                
                print(error)
                failure()
        }
        
    }
    
}
